package com.zingrow.web.configure.keyword.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;

import com.idaycrm.idaybase.utils.JsonUtils;
import com.zingrow.common.ReturnStandardDataFormat;
import com.zingrow.common.utils.CommonUtils;
import com.zingrow.common.utils.EncodingUtils;
import com.zingrow.common.utils.OptClass;
import com.zingrow.common.utils.PageView;
import com.zingrow.web.base.CodeMsg;
import com.zingrow.web.base.controller.BaseController;
import com.zingrow.web.base.enums.Menu;
import com.zingrow.web.base.enums.Operation;
import com.zingrow.web.common.utils.AnalyzeResult;
import com.zingrow.web.configure.channel.model.Channel;
import com.zingrow.web.configure.keyword.model.Keyword;
import com.zingrow.web.configure.keyword.service.IKeywordService;
import com.zingrow.web.support.operate.model.OptRecord;
import com.zingrow.web.support.operate.service.IOptRecordService;
import com.zingrow.web.user.model.ActiveUser;
import com.zingrow.web.user.model.UserPermission;
import com.zingrow.web.user.service.IPermissionService;

/**
 * 
 * 元搜索处理器
 *
 * @author shengchen
 *
 * @time:2016年12月26日 下午1:26:38
 */
@Controller
@RequestMapping(value = "/Keyword/", produces = "application/json;charset=UTF-8")
public class KeywordController extends BaseController {

	@Autowired
	private IKeywordService keywordService;

	@Autowired
	private IOptRecordService optRecordService;
	@Autowired
	private IPermissionService permissionService;
	@Autowired
	private IOptRecordService ioptRecordService;

	/**
	 * 分页查询
	 * 
	 * @param httpRequest
	 * @param response
	 * @param pageIndex
	 * @param pageSize
	 * @param keywords_seek
	 * @param keywords_status
	 * @return
	 */
	@ResponseBody
	@RequestMapping("queryByParams")
	public String queryByParams(HttpServletRequest httpRequest, HttpServletResponse response, Integer pageIndex,
			Integer pageSize, String keywords_seek, Integer keywords_status,String sp) {
		List<Keyword> returnList = new ArrayList<>();
		ReturnStandardDataFormat standardData = new ReturnStandardDataFormat(CodeMsg.CODE_ERROR, CodeMsg.MSG_ERROR,
				returnList);
		PageView pageView = null;

		try {
			if (pageIndex == null || pageIndex <= 0) {
				pageIndex = 1;
			}
			if (pageSize == null || pageSize <= 0) {
				pageSize = 10;
			}
			pageView = new PageView(pageSize, pageIndex);
			if (keywords_seek != null || "".equals(keywords_seek)) {
				keywords_seek = EncodingUtils.fixUrlParamEncoding(httpRequest, keywords_seek);
			}
			returnList = keywordService.queryByParams(pageView, keywords_seek, keywords_status);
			if("1".equals(sp))
			{
				//新增一条操作记录
				ActiveUser opuser = getUser(httpRequest);//获取操作用户
				OptRecord s = new OptClass().yss_query(opuser,Menu.Resourceallocation.toString(),
						Menu.Metasearch.toString(),Operation.query.toString(),keywords_seek);
				if(!s.getOptName().equals("null"))	
				ioptRecordService.insert(s);
			}
		} catch (Exception e) {
			log.error("根据参数查询发生异常");
			ActiveUser opuser = getUser(httpRequest);//获取操作用户
			OptRecord s = new OptClass().recordabnormality(opuser,"元搜素配置根据参数查询异常");
			ioptRecordService.insert(s);
			standardData.setReturnCode(CodeMsg.CODE_EXCEPTION);
			standardData.setReturnMessage(CodeMsg.MSG_EXCEPTION);
			standardData.setReturnData(returnList);
		}

		// 执行到这代表成功，返回查询成功
		standardData.setReturnData(returnList);
		standardData.setReturnCode(CodeMsg.CODE_OK);
		standardData.setReturnMessage(CodeMsg.MSG_OK);
		standardData.setTotalPages(pageView.getPageCount());
		standardData.setTotalRecords(pageView.getRowCount());
		return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
	}

	/**
	 * 新增一个关键词
	 * 
	 * @param httpRequest
	 * @param response
	 * @param metasearch
	 * @return
	 */
	@ResponseBody

	@RequestMapping("addKeyword")
	public String addKeyword(HttpServletRequest httpRequest, HttpServletResponse response, Keyword keyword) {
		ReturnStandardDataFormat standardData = new ReturnStandardDataFormat(CodeMsg.CODE_ERROR, CodeMsg.MSG_ERROR,
				null);
		try {
			if (CommonUtils.isStrNull(keyword.getKeywords_seek())) {
				// 判断传入参数合法性
				standardData.setReturnCode(CodeMsg.CODE_ERROR_PARAMS);
				standardData.setReturnMessage(CodeMsg.MSG_ERROR_PARAMS);
				return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
			}
			if (keyword.getKeywords_seek() != null || "".equals(keyword.getKeywords_seek())) {
				keyword.setKeywords_seek(EncodingUtils.fixUrlParamEncoding(httpRequest, keyword.getKeywords_seek()));
			}
			if (keyword.getKeywords_type() != null || "".equals(keyword.getKeywords_type())) {
				keyword.setKeywords_type(EncodingUtils.fixUrlParamEncoding(httpRequest, keyword.getKeywords_type()));
			}
			if (keywordService.querySameByMetasearchKeywords(keyword.getKeywords_seek(), null)) {
				// 检测到有除此信息之外的同名数据
				standardData.setReturnCode(CodeMsg.CODE_ERROR_OTHER);
				standardData.setReturnMessage("新增失败，已存在其他相同关键词！");
				return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
			}
			if (keywordService.addMetasearch(keyword)) {
				// // 添加操作记录
				// // 操作成功
				ActiveUser opuser = getUser(httpRequest);//获取操作用户
				OptRecord s = new OptClass().yss_add(opuser,Menu.Resourceallocation.toString(),
						Menu.Metasearch.toString(),Operation.insert.toString(),keyword);
				ioptRecordService.insert(s);
				standardData.setReturnCode(CodeMsg.CODE_OK);
				standardData.setReturnMessage(CodeMsg.MSG_OK);
			} else {
				ActiveUser opuser = getUser(httpRequest);//获取操作用户
				OptRecord s = new OptClass().recordabnormality(opuser,"频道配置新增失败");
				ioptRecordService.insert(s);
				standardData.setReturnCode(CodeMsg.CODE_ERROR);
				standardData.setReturnMessage(CodeMsg.MSG_ERROR);
			}
		} catch (Exception e) {
			log.error("新增关键词异常");
			ActiveUser opuser = getUser(httpRequest);//获取操作用户
			OptRecord s = new OptClass().recordabnormality(opuser,"元搜索配置新增异常");
			ioptRecordService.insert(s);
			standardData.setReturnCode(CodeMsg.CODE_EXCEPTION);
			standardData.setReturnMessage(CodeMsg.MSG_EXCEPTION);
		}
		return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
	}

	/**
	 * 根据关键词ID修改配置信息
	 * 
	 * @param httpRequest
	 * @param response
	 * @param metasearch
	 * @return
	 */
	@ResponseBody
	@RequestMapping("modifyKeyword")
	public String modifyByKeywordId(HttpServletRequest httpRequest, HttpServletResponse response, Keyword keyword) {
		ReturnStandardDataFormat standardData = new ReturnStandardDataFormat(CodeMsg.CODE_ERROR, CodeMsg.MSG_ERROR,
				null);
		try {

			if (CommonUtils.isStrNull(keyword.getKeywords_seek())) {
				// 判断传入参数合法性
				standardData.setReturnCode(CodeMsg.CODE_ERROR_PARAMS);
				standardData.setReturnMessage(CodeMsg.MSG_ERROR_PARAMS);
				return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
			}
			if (keyword.getKeywords_seek() != null || "".equals(keyword.getKeywords_seek())) {
				keyword.setKeywords_seek(EncodingUtils.fixUrlParamEncoding(httpRequest, keyword.getKeywords_seek()));
			}
			if (keywordService.querySameByMetasearchKeywords(keyword.getKeywords_seek(), keyword.getKeywords_id())) {
				// 检测到有除此信息之外的同名数据
				standardData.setReturnCode(CodeMsg.CODE_ERROR_OTHER);
				standardData.setReturnMessage("修改失败，已存在其他相同关键词！");
				return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
			}
			Keyword ykeyword=keywordService.queryById(keyword.getKeywords_id());
			if (keywordService.modifyByPrimaryKey(keyword)) {
				// // 添加操作记录
				ActiveUser opuser = getUser(httpRequest);//获取操作用户
				OptRecord s = new OptClass().yss_updata(opuser,Menu.Resourceallocation.toString(),
						Menu.Metasearch.toString(),Operation.update.toString(),ykeyword,keyword);
				ioptRecordService.insert(s);	
				// // 操作成功
				standardData.setReturnCode(CodeMsg.CODE_OK);
				standardData.setReturnMessage(CodeMsg.MSG_OK);
			} else {
				standardData.setReturnCode(CodeMsg.CODE_ERROR);
				standardData.setReturnMessage(CodeMsg.MSG_ERROR);
			}
		} catch (Exception e) {
			log.error("修改关键词异常");
			ActiveUser opuser = getUser(httpRequest);//获取操作用户
			OptRecord s = new OptClass().recordabnormality(opuser,"元搜索配置修改异常");
			ioptRecordService.insert(s);
			standardData.setReturnCode(CodeMsg.CODE_EXCEPTION);
			standardData.setReturnMessage(CodeMsg.MSG_EXCEPTION);
		}
		return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
	}

	/**
	 * 删除一个微信配置信息关键词
	 * 
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("deleteKeyword")
	public String deleteUser(HttpServletRequest httpRequest, HttpServletResponse response, Integer keywords_id,
			String keywords_seek) {
		ReturnStandardDataFormat standardData = new ReturnStandardDataFormat(CodeMsg.CODE_ERROR, CodeMsg.MSG_ERROR,
				null);
		try {
			if (CommonUtils.isObjectNull(keywords_id)) {
				// 判断传入参数合法性
				standardData.setReturnCode(CodeMsg.CODE_ERROR_PARAMS);
				standardData.setReturnMessage(CodeMsg.MSG_ERROR_PARAMS);
				return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
			}
			Keyword keyword=keywordService.queryById(keywords_id);
			if (keywordService.deleteMetasearch(keywords_id)) {
				// // 添加操作记录
				ActiveUser opuser = getUser(httpRequest);//获取操作用户
				OptRecord s = new OptClass().yss_delete(opuser,Menu.Resourceallocation.toString(),
						Menu.Metasearch.toString(),Operation.delete.toString(),keyword);
				ioptRecordService.insert(s);	
				// // 操作成功
				standardData.setReturnCode(CodeMsg.CODE_OK);
				standardData.setReturnMessage(CodeMsg.MSG_OK);
			} else {
				ActiveUser opuser = getUser(httpRequest);//获取操作用户
				OptRecord s = new OptClass().recordabnormality(opuser,"元搜索配置删除失败");
				ioptRecordService.insert(s);
				standardData.setReturnCode(CodeMsg.CODE_ERROR);
				standardData.setReturnMessage(CodeMsg.MSG_ERROR);
			}
		} catch (Exception e) {
			log.error("删除关键词异常");
			log.error(e.getMessage());
			standardData.setReturnCode(CodeMsg.CODE_EXCEPTION);
			standardData.setReturnMessage(CodeMsg.MSG_EXCEPTION);
		}
		return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
	}

	/* yzx 元搜索关键词导入 */
	@ResponseBody
	@RequestMapping("importExcelModel")
	public String importExcelModel(HttpServletRequest request, HttpServletResponse response) {
		ReturnStandardDataFormat standardData = new ReturnStandardDataFormat(CodeMsg.CODE_ERROR, CodeMsg.MSG_ERROR,
				null);
		// 获取Web项目的全路径
		String realPath = request.getSession().getServletContext().getRealPath("/uploadTemp/");
		File saveFile = null;
		// 如果目录不存在就创建
		if (!new File(realPath).exists()) {
			new File(realPath).mkdir();
		}
		saveFile = new File(new File(realPath),
				getUser(request).getUserAccount() + System.currentTimeMillis() + "keyword_temp.xls");
		// 把request转型
		DefaultMultipartHttpServletRequest multipartRequest = (DefaultMultipartHttpServletRequest) request;
		// 获得文件
		MultipartFile multipartFile = multipartRequest.getFile("importExcel");
		// 保存解析出来的信息
		AnalyzeResult<Keyword> analyzeResult = new AnalyzeResult<Keyword>(true, "", new ArrayList<Keyword>());
		// 接收导入失败的数据，成功此list的size为0，否则里面的数据为错误数据
		List<Integer> errorIndexList = new ArrayList<Integer>();
		try {
			// 转换成file
			multipartFile.transferTo(saveFile);
			// 进行数据检测,将数据写入analyzeResult.list中
			keywordService.analyzeExcelData(saveFile, analyzeResult);
			if (analyzeResult.isSuccess()) {
				List<Keyword> list = analyzeResult.getList();
				for (int i = 0; i < list.size(); i++) {
					int sum = 0;
					int s = 0;
					// 判断数据库重复
					if (keywordService.querySameByMetasearchKeywords(list.get(i).getKeywords_seek(),
							list.get(i).getKeywords_id())) {
						standardData.setReturnCode(CodeMsg.CODE_ERROR_OTHER);
						standardData.setReturnMessage("Excel中频道URL或频道名称有重复值" + (i + 2) + "行");
						return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
					}
					// 判断excel表重复
					for (Keyword key : list) {
						if (key.getKeywords_seek().equals(list.get(i).getKeywords_seek())) {
							s = 1;
						} else {
							s = 0;
						}
						sum += s;
					}					
					if(sum>1){
						standardData.setReturnCode(CodeMsg.CODE_ERROR_OTHER);
						standardData.setReturnMessage("Excel表中有重复值"+list.get(i).getKeywords_seek());
						return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
					}
				}
				for (Keyword key : list) {
					keywordService.addMetasearch(key);
				}
				if (errorIndexList.size() == 0) {
					ActiveUser opuser = getUser(request);//获取操作用户
					OptRecord s = new OptClass().goiss(opuser,Menu.Resourceallocation.toString(),
							Menu.Metasearch.toString(),Operation.daoru.toString(),list.size());
					ioptRecordService.insert(s);	
					// 导入数据成功
					standardData.setReturnCode(CodeMsg.CODE_OK);
					standardData.setReturnMessage(CodeMsg.MSG_OK);
					return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
				} else {
					ActiveUser opuser = getUser(request);//获取操作用户
					OptRecord s = new OptClass().goiss(opuser,Menu.Resourceallocation.toString(),
							Menu.Metasearch.toString(),Operation.daoru.toString(),list.size()-errorIndexList.size());
					ioptRecordService.insert(s);	
					// 有导入错误返回错误行数
					standardData.setReturnCode(CodeMsg.CODE_ERROR_SAME);
					standardData.setReturnMessage("导入数据完成，存在部分数据导入失败：" + errorIndexList.size());
				}
			} else {
				// 检测数据失败，返回相应提示信息
				standardData.setReturnCode(CodeMsg.CODE_ERROR_OTHER);
				standardData.setReturnMessage("检测数据格式错误：" + analyzeResult.getErrorMessage());
			}
		} catch (Exception e) {
			log.error("导入频道信息异常");
			ActiveUser opuser = getUser(request);//获取操作用户
			OptRecord s = new OptClass().recordabnormality(opuser,"元搜索配置导入信息异常");
			ioptRecordService.insert(s);
			standardData.setReturnCode(CodeMsg.CODE_ERROR);
			standardData.setReturnMessage(CodeMsg.MSG_ERROR);
		} finally {
			// 结束后删除本地文件
			saveFile.delete();
		}
		return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
	}
}
